<template>
  <div>
    <van-form>
      <van-field
        v-model="info.phone"
        name="手机号"
        label="手机号"
        placeholder="手机号"
        :rules="[{ validator , message: '请填写手机号' }]"
      />
      <div class="left">
        <van-field
          v-model="info.code"
          name="验证码"
          label="验证码"
          placeholder="验证码"
          :rules="[{ required: true, message: '请填写验证码' }]"
        />
        <van-button
          type="info"
          native-type="submit"
          @click="handelsendCode"
          class="btn"
          :disabled="disabled"
        >{{btntext}}</van-button>
      </div>

      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit" @click="onsubmit">登录</van-button>
      </div>
    </van-form>
  
  </div>
</template>
<script>
import { login,getcode } from "../api/user";
export default {
  data() {
    return {
      info: {
        phone: "",
        code: ""
      },
 
      btntext: "发送验证码",
      disabled: false,
      checkCode:null,
      
    };
  },
  methods: {
    // 手机号校验规则
    validator(value) {
      console.log(value)
      return /^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(value);
    },
    onsubmit() {
      //前后端code值不一样转义
      if(this.checkCode*1 === this.info.code*1){
        login(this.info).then(response => {
        // console.log(response.code,response.msg)
        console.log(response);
        // alert("登录成功")
        // console.log(this.$route)
        // if(response.data.code){
//保存token值
        localStorage.setItem("token", response.data);
        this.$router.push("/");
        this.$toast.success(response.message);
        // }
      });
      }else{
        this.$toast('验证码错误');
      }
    },
    // 发送验证码按钮
    handelsendCode() {
      // 首先判断如果没有输入手机号
      if(!this.info.phone){
        // 弹出提示 
        this.$toast('请输入手机号');
        return
        // 判断 输入的手机号是否正确 如果不正确
      }else if(!this.validator(this.info.phone)){
        // 弹出提示
        this.$toast('请输入正确的手机号');
        return 
      }
      // this.btnsble = true; //开启禁用的按钮
      //定义倒计时间,不能写逗号
      let timeout = 30;
      //定时器
      let timer = null;
      //禁用按钮
      this.disabled = true;
      // 获取验证码
      this.getCode()

      timer = setInterval(() => {
        //倒计时时间-1
        timeout = timeout - 1;
        this.btntext = `${timeout}s后重试`;
        // 如果倒计时时间为0的话，清除定时器
        if (timeout <= 0) {
          clearInterval(timer);
          this.btntext = "发送验证码";
          this.disabled = false;
          
        }

        //随机小数
      }, 1000);
    },
    getCode(){
      getcode().then(response =>{
        console.log(response)
        this.checkCode = response.data
          this.$toast(`验证码:${response.data}`);
      })
    }
  },
  created(){
  }
};
</script>
<style lang="scss">
.left {
  display: flex;
}
.btn{
  width: 200px;
  height: 180px;
 
}
.van-button__text{
  color: #000;
  
}
</style>
